import json
from decimal import Decimal

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from cloudLibraryDjango import common
from newbooksrecd.models import TBook


def getList(request):
    userName = request.session.get("user_name")
    return render(request, 'booksBorrow/list.html', locals())


# 查询用户列表，带分页
def list(request):
    # 表格要展现的数据
    books = TBook.objects.all()
    # 处理成LayUi官方文档的格式
    lis = commonList(books)

    res = common.getPageData(request, books, lis)
    result = common.getResult(books.count(), res)

    return HttpResponse(json.dumps(result))


def searchList(request):
    # 表格要展现的数据
    newBooks = TBook.objects.all()

    bookName = request.GET.get("bookName")
    if bookName:
        newBooks = newBooks.filter(book_name=bookName)

    bookStatus = request.GET.get("bookStatus")
    if bookStatus:
        newBooks = newBooks.filter(book_status=bookStatus)

    res = commonList(newBooks)

    # 放在一个列表里
    result = common.getResult(newBooks.count(), res)
    return JsonResponse(result)


# 跳转到修改页面
def show_edit(request, bookId):
    book = TBook.objects.get(book_id=bookId)
    return render(request, 'booksBorrow/edit.html', locals())


def edit(request):
    if request.POST:
        id = request.POST.get("bookId")
        if id is None:
            result = {"code": 1, "msg": "请选择要修改的数据"}
            return JsonResponse(result)
        # 查询图书
        book = TBook.objects.get(pk=id)

        bookName = request.POST.get("bookName")
        if bookName:
            book.book_name = bookName

        bookIsbn = request.POST.get("bookIsbn")
        if bookIsbn:
            book.book_isbn = bookIsbn

        bookAuthor = request.POST.get("bookAuthor")
        if bookAuthor:
            book.book_author = bookAuthor

        bookPress = request.POST.get("bookPress")
        if bookPress:
            book.book_press = bookPress

        bookPrice = request.POST.get("bookPrice")
        if bookPrice:
            book.book_price = Decimal(bookPrice)

        bookPagination = request.POST.get("bookPagination")
        if bookPagination:
            book.book_pagination = bookPagination

        bookUploadTime = request.POST.get("bookUploadtime")
        if bookUploadTime:
            book.book_uploadtime = bookUploadTime

        bookStatus = request.POST.get("bookStatus")

        # 判断如果图书状态为已下架，则修改的时候，将其图书状态变更为可借阅状态
        if book.book_status == '3':
            book.book_status = '0'
        elif bookStatus:
            book.book_status = bookStatus

        book.save()
        result = {"code": 0, "msg": "修改成功"}
        return JsonResponse(result)

    result = {"code": 1, "msg": "修改失败"}
    return JsonResponse(result)


def commonList(books):
    res = []
    for book in books:
        data = dict()
        data['bookId'] = book.book_id
        data['bookName'] = book.book_name
        data['isbn'] = book.book_isbn
        bookStatus = book.book_status
        if bookStatus == '0':
            status = "可借阅"
        elif bookStatus == '1':
            status = "借阅中"
        elif bookStatus == '2':
            status = "归还中"
        else:
            status = "已下架"
        data['bookStatus'] = status

        data['status'] = book.book_status

        if book.book_borrower is None:
            data['borrower'] = ""
        else:
            data['borrower'] = book.book_borrower.user_name
        data['price'] = book.book_price
        data['author'] = book.book_author
        data['publish'] = book.book_press
        data['bookPages'] = book.book_pagination
        data['publishDate'] = book.book_uploadtime
        data['borrowTime'] = book.book_borrowtime
        data['returnTime'] = book.book_returntime
        res.append(data)
    return res
